import React, { useState, useRef, useEffect } from 'react';
import styled from 'styled-components';
import { getLabelWidthCanvas } from '../../../utils/string';

interface AutoScalingTextProps {
    children: string;
    className?: string;
    textClassName?: string;
    prefix?: React.ReactNode
    calScale?: (scale: number) => void
}

const Container = styled.div<{ scale: number }>`
  display: inline-block;
  position: relative;
  transform: scale(${props => props.scale});
`;

const Text = styled.div`
    font-weight: 600;
    font-size: .875rem;
    color: white;
`

const AutoScaleItem: React.FC<AutoScalingTextProps> = ({ children, prefix, className, textClassName, calScale }) => {
    const containerRef = useRef<HTMLDivElement>(null);
    const textRef = useRef<HTMLDivElement>(null);
    const [scale, setScale] = useState(1);

    useEffect(() => {
        const container = containerRef.current;
        const text = textRef.current;
        if (container && text) {
            const containerWidth = container.offsetWidth;
            // const textWidth = text.offsetWidth;
            const font = window.getComputedStyle(text).font;
            const textWidth = getLabelWidthCanvas([children], font);
            const textX = text.offsetLeft
            const s = textX + textWidth > containerWidth ? containerWidth / (textX + textWidth) : 1
            // calScale ? calScale(s) : setScale(s)
            setScale(s)
        }
    }, [calScale, children]);

    return (
        <Container
            ref={containerRef}
            className={className}
            scale={scale}
        >
            {prefix}
            <Text
                className={textClassName}
                ref={textRef}
            >
                {children}
            </Text>
        </Container>
    );
};

export default AutoScaleItem;
